#!/bin/sh /etc/rc.common

START=98
USE_PROCD=1

enable_lan_ping() {
	uci -q set firewall.floatip_lan_offline.enabled=0 || return 0
	uci changes | grep -Fq 'firewall.floatip_lan_offline.enabled' || return 0
	uci commit firewall
	/etc/init.d/firewall reload
}

start_service() {
	config_load floatip
	config_get_bool enabled "main" enabled 0
	ifdown floatip
	[[ "$enabled" = 1 ]] || {
		enable_lan_ping
		return 0
	}
	[[ "`uci -q get network.lan.proto`" = "static" ]] || {
		logger -s -t floatip "LAN proto is not static"
		return 0
	}
	local set_ip set_prefix
	config_get set_ip "main" set_ip
	[[ -n "$set_ip" ]] || return 0
	if [[ "$set_ip" = "*/*" ]]; then
		eval "$(ipcalc.sh "$set_ip" )";set_prefix=$PREFIX;set_ip=$IP
	else
		set_prefix=32
	fi
	local lan_ip="`uci -q get network.lan.ipaddr`"
	[[ -n "$lan_ip" ]] || return 0
	local lan_net lan_prefix set_net ip
	local in_range=0
	local lan_netmask="`uci -q get network.lan.netmask`"
	for ip in $lan_ip; do
		if [[ "$ip" = "*/*" ]]; then
			eval "$(ipcalc.sh $ip )";lan_net=$NETWORK;lan_prefix=$PREFIX
		else
			# prefix=32 if not present
			[[ -n "$lan_netmask" ]] || continue
			eval "$(ipcalc.sh $ip $lan_netmask )";lan_net=$NETWORK;lan_prefix=$PREFIX
		fi
		[[ "$set_prefix" -ge "$lan_prefix" ]] || continue
		eval "$(ipcalc.sh $set_ip/$lan_prefix )";set_net=$NETWORK
		[[ "$set_net" = "$lan_net" ]] && {
			[[ "$set_prefix" = 32 ]] && set_prefix=$lan_prefix
			in_range=1
			break
		}
	done

	[[ $in_range = 1 ]] || {
		logger -s -t floatip "float ip is not belong to any LAN subnets"
		return 0
	}
	procd_open_instance
	procd_set_param command /usr/libexec/floatip.sh "$set_prefix"
	procd_set_param stderr 1
	procd_set_param file /etc/config/floatip
	procd_close_instance
}

stop_service() {
	enable_lan_ping
	ifdown floatip
}

service_triggers() {
	procd_add_reload_trigger "network" "floatip"
}
